package com.qf.team2.netdisc.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.team2.netdisc.common.exception.BusinessException;
import com.qf.team2.netdisc.common.pojo.entity.AlipayOrder;
import com.qf.team2.netdisc.common.pojo.qo.AlipayOrderQO;
import com.qf.team2.netdisc.config.AlipayConfig;
import com.qf.team2.netdisc.dao.AlipayOrderMapper;
import com.qf.team2.netdisc.service.AlipayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 支付宝订单服务实现类
 *
 * @author Simon_Wong
 * @date 2021/05/25 16:48
 */
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Service
public class AlipayOrderServiceImpl implements AlipayOrderService {

    @Autowired
    private AlipayOrderMapper alipayOrderMapper;

    @Override
    public String aliPay(AlipayOrder alipayOrder) throws AlipayApiException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = alipayOrder.getOut_trade_no();
        //付款金额，必填
        String total_amount = String.valueOf(alipayOrder.getTotal_amount());
        //订单名称，必填
        String subject = alipayOrder.getSubject();
        //商品描述，可空
        String body = alipayOrder.getBody();

        //若想给BizContent增加其他可选请求参数，可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"10m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        return alipayClient.pageExecute(alipayRequest).getBody();
    }

    @Override
    public AlipayOrderQO addOrder(AlipayOrderQO alipayOrderQO) {
        alipayOrderMapper.insertOrder(
                alipayOrderQO);
        return alipayOrderQO;
    }

    @Override
    public AlipayOrder setOrderStatus(Integer orderId, int status) {
        if (alipayOrderMapper.updateOrder(orderId, status) != 1) {
            throw new BusinessException("未知错误");
        }
        AlipayOrder order = alipayOrderMapper.selectOrder(orderId);
        if (order == null) {
            throw new BusinessException("找不到该订单");
        }
        return order;
    }
}
